package hd.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.lang.reflect.Field;

/**
 * 屏幕分辨率等信息处理
 * <p/>
 * Created by haidy on 14-8-20.
 */
public class ScreenHelper {

    /**
     * dp转换为px
     *
     * @param context 上下文
     * @param dp      dip
     * @return px
     */
    public static int dp2px(Context context, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
    }


    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
            return statusBarHeight;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 截屏
     *
     * @param v 视图对象
     * @return 图片
     */
    public synchronized static Bitmap screenShot(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        try {
            v.draw(canvas);
        } catch (Exception e) {
            if (bitmap != null && !bitmap.isRecycled())
                bitmap.recycle();
            bitmap = null;
        }
        return bitmap;
    }

    /**
     * 打开输入法
     *
     * @param view View
     */
    public static void openInputMethod(View view) {
        try {
            InputMethodManager imm = (InputMethodManager) view.getContext().
                    getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        } catch (Exception ignored) {
        }
    }

    /**
     * 关闭输入法
     *
     * @param view view
     */
    public static void closeInputMethod(View view) {
        try {
            if (((Activity) view.getContext()).getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception ignored) {
        }
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context                                  上下文
     * @param spValue（DisplayMetrics类中属性scaledDensity）
     * @return px
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取字体的高度
     *
     * @param fontSize 字体大小
     * @return 字体的高度
     */
    public static int getFontHeight(float fontSize) {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        Paint.FontMetrics fm = paint.getFontMetrics();
        return (int) Math.ceil(fm.descent - fm.top) + 2;
    }

    /**
     * 获取字符串的宽度
     *
     * @param fontSize 字体大小
     * @param str      字符串
     * @return 字符串的长度
     */
    public static float getFontWidth(int fontSize, String str) {
        Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextSize(fontSize);
        Rect rect = new Rect();
        mTextPaint.getTextBounds(str,0,str.length(),rect);
        return rect.width();
    }

}
